//
//  XYPastTimeFormatter.swift
//  XYReadBook
//
//  Created by fox on 2017/9/8.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit
let hmdateFormatter = DateFormatter()
var hmcalendar = Calendar.current
class XYPastTimeFormatter: Formatter {
    static let calendar = Calendar(identifier: Calendar.Identifier.iso8601)
    
    static let shared = XYPastTimeFormatter()
    
    override func string(for obj: Any?) -> String? {
        guard let date = obj as? Date else {
            return nil
        }
        let dc = XYPastTimeFormatter.calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date, to: Date())
        if let y = dc.year, y >= 1 {
            return "\(y)年前"
        } else if let m = dc.month, m >= 1 {
            return "\(m)月前"
        } else if let d = dc.day, d >= 1 {
            return "\(d)天前"
        } else if let h = dc.hour, h >= 1 {
            return "\(h)小时前"
        } else if let m = dc.minute, m >= 10 {
            return "\(m)分钟前"
        } else {
            return "刚刚"
        }
    }
    override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
        return false
    }
    
    
    
    /// 将字符串转成时间
    ///
    /// - Parameter sinaTimeStr: "yyy-MM-dd'T'HH:mm:ss"
    /// - Returns: NSDate
    static func sinaTimeStrToDate (sinaTimeStr: String) -> NSDate {
        let formatStr = "yyyy-MM-dd'T'HH:mm:ss"
        hmdateFormatter.dateFormat = formatStr
        hmdateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 60*60*8) as TimeZone!
        //下面的这个属性必须传,不然在真机上时间可能不准确
        hmdateFormatter.locale = NSLocale(localeIdentifier: "en") as Locale!
        
        return hmdateFormatter.date(from: sinaTimeStr)! as NSDate
    }

}
